package io.contract.websocket;

import com.alibaba.fastjson2.JSONObject;
import io.contract.dto.BinanceKlineEvent;
import io.contract.service.BinanceService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

@Slf4j
public class BinanceKlineWebSocketClient extends WebSocketClient {

    private final BinanceService binanceService;

    public BinanceKlineWebSocketClient(URI serverUri, BinanceService binanceService) {
        super(serverUri);
        this.binanceService = binanceService;
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        log.info("Connected to Binance WebSocket");
    }

    @Override
    public void onMessage(String message) {
        log.info("Received message: " + message);
        // 处理接收到的K线数据
        JSONObject jsonObject = JSONObject.parseObject(message);
        String e = jsonObject.getString("e");
        if (e.equals("kline")) {
//            bizUserInfoService.saveData(jsonObject);
            BinanceKlineEvent kLine = binanceService.getKLine(jsonObject.toJSONString());
            log.info("Kline: " + kLine.toString());
        }
    }

    @SneakyThrows
    @Override
    public void onClose(int code, String reason, boolean remote) {
        log.info("WebSocket connection closed with exit code " + code + " additional info: " + reason);
        URI uri = new URI("wss://stream.binance.com:9443/ws/btcusdt@kline_1s");
        BinanceKlineWebSocketClient client = new BinanceKlineWebSocketClient(uri, binanceService);
        client.connect();
    }

    @Override
    public void onError(Exception ex) {
        log.info("An error occurred:" + ex.getMessage());
        ex.printStackTrace();
    }

}
